//
//  Api.m
//  News
//
//  Created by  yanguang on 14/6/13.
//  Copyright (c) 2013 yyt. All rights reserved.
//
#import "Api.h"
#import <AFNetworking/AFNetworking.h>
#import "URLPath.h"
#import "AppDelegate.h"
//#import "UserModel.h"
//#import "JSONKit.h"
//#import "ChatModel.h"

// MARK: tools
//#import "SBJson.h"
//#import "TSErrorCode.h"

typedef enum {
    HttpRequestStatusNormal = 0 ///< 正常状态,所有非 0 状态为错误
} HttpRequestStatus;

const NSString *kStatuskey = @"status";
const NSString *kStatusMsgKey = @"msg";
const NSString *kStatusDataKey = @"data";

@implementation Api

//void(^ apiProcessResponseData)(id,void(^)(id),void(^)(NSError *)) = ^(id data,void(^success)(id),void(^fail)(NSError *)) {
//    if (![data isKindOfClass:[NSDictionary class]]) {
//        if (fail) {
//            fail([TSErrorCode errorCreateWithCoustomDomain:@"ZBURLErrorDomain" errorCode:505 description:@"服务器返回的数据格式有误"]);
//        }
//        return;
//    }
//    NSDictionary *responseData = (NSDictionary *)data;
//    if ([responseData[kStatuskey] integerValue] == HttpRequestStatusNormal) {
//        if (success) {
//            success(responseData[kStatusDataKey]);
//        }
//    } else {
//        if (fail) {
//            fail([TSErrorCode errorCreateWithCoustomDomain:@"TSURLErrorDomain" errorCode:[data[kStatuskey] integerValue] description:data[kStatusMsgKey]]);
//        }
//    }
//};

+ (void)requestWithMethod:(NSString*)method
                 withPath:(NSString*)path
               withParams:(NSDictionary*)params
              withSuccess:(void (^)(id responseObject))success
                withError:(void (^)(NSError* error))failed
{
	
    NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:params];
//    if (SWNOTEmptyStr([UserModel oauthToken])) {
//        [mutableDic setObject:[UserModel oauthToken] forKey:@"oauth_token"];
//        [mutableDic setObject:[UserModel oauthTokenSecret] forKey:@"oauth_token_secret"];
//    }
    
    // FIXME: 主要能够实现 acceptableContentTypes 能解析 "text/html"
    AFHTTPSessionManager *httpSessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:HEADURL]];
    
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain",@"text/html", @"application/x-www-form-urlencoded", @"text/javascript", nil];
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    requestSerializer.timeoutInterval = 10;
    
    httpSessionManager.requestSerializer = requestSerializer;
    httpSessionManager.responseSerializer = responseSerializer;
    
    
    if ([[method lowercaseString] isEqualToString:@"get"])
    {
        httpSessionManager.requestSerializer.timeoutInterval = 10;
        
        [httpSessionManager GET:path parameters:mutableDic progress:^(NSProgress * _Nonnull downloadProgress) {
            //
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (SWNOTEmptyDictionary(responseObject)&&responseObject[@"code"]) {
                    NSLog(@"param %@   path %@",mutableDic,path);
                    
                    NSInteger status = [responseObject[@"status"] integerValue];

                    // 登录信息失效,很可能是其他
                    if (status == 403) {
                        // 展示提示框
//                        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//                        [appDelegate.noticeLogoutAlert show];
                        
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"LOGOUT" object:nil];
                        
                        return ;
                        
                    }
                }
            });

            
            dispatch_async(dispatch_get_main_queue(), ^{
                success(responseObject);
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //
            dispatch_async(dispatch_get_main_queue(), ^{
//                shareChat.wsConnet = NO;//没网了，socket肯定也断开了
                failed(error);
            });

        }];
        

    }
    else if ([[method lowercaseString] isEqualToString:@"post"])
    {
        [httpSessionManager POST:path parameters:mutableDic progress:^(NSProgress * _Nonnull uploadProgress) {
            //
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //
            dispatch_async(dispatch_get_main_queue(), ^{
                success(responseObject);
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //
            dispatch_async(dispatch_get_main_queue(), ^{
//                shareChat.wsConnet = NO;//没网了，socket肯定也断开了
                failed(error);
            });

        }];
    }
}


@end
